package com.mjk.common.core.rmq.mq;



import com.mjk.common.base.error.BizException;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.logger.BizLogger;

import java.lang.reflect.Method;

public class EventHandler {
	private final Object target;

	private final Method method;

	public EventHandler(Object target, Method method) {
		this.target = target;
		this.method = method;
		method.setAccessible(true);
	}
	public void handle(String eventName,boolean isJsonType,String message,Object event)  {
		preHandle(event);
		try {
			if (isJsonType){
				Class<?> clazz = Class.forName(eventName);
				Object object = GsonUtils.json2Bean(message, clazz);
				method.invoke(target, object);
			}else {
				method.invoke(target, event);
			}
		} catch (IllegalArgumentException e) {
			throw new BizException("Method rejected target/argument: " + event);
		} catch (IllegalAccessException e) {
			throw new BizException("Method became inaccessible: " + event);
		} catch (Exception e) {
			throw new BizException(BizLogger.error(e));
		} finally {
			afterHandle(event);
		}
	}

	protected void afterHandle(Object event) {
		// 后置
	}

	protected void preHandle(Object event) {
		// 前置
	}

	@Override
	public int hashCode() {
		final int PRIME = 31;
		return (PRIME + method.hashCode()) * PRIME + target.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}

		final EventHandler other = (EventHandler) obj;
		return method.equals(other.method) && target == other.target;
	}

	public String expression() {
		return target.getClass().getCanonicalName() + "#" + method.getName();
	}
}
